package com.taotao.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DataFormat {
    public static void main(String[] args) throws ParseException {
        String currentTime = String.format("%tF%n", new Date(System.currentTimeMillis()));
        System.out.println("当前时间:" + currentTime);
        String result = getDayDiff("2019-11-25 12:33", currentTime);
        System.out.println("显示的时间格式:" + result);
    }

    /**
     * 得到时间差 yyyy-MM-dd 格式
     *
     * @param time
     * @return
     * @throws ParseException
     */
    public static String getDayDiff(String time) throws ParseException {
        String currentTime = String.format("%tF%n", new Date(System.currentTimeMillis()));
        return getDayDiff(time, currentTime);
    }

    /**
     * 得到时间差 yyyy-MM-dd 格式
     *
     * @param fDateStr 需要计算的时间
     * @param oDateStr 应该传入当前时间
     * @throws ParseException
     * @return 
     */
    public static String getDayDiff(String fDateStr, String oDateStr) throws ParseException {
        int result = daysOfTwo(fDateStr, oDateStr);
        String timeResult = "";
        switch (result) {
            case -1:
                timeResult = "请检查时间";
                break;
            case 0:
                timeResult = "今天";
                break;
            case 1:
                timeResult = "昨天";
                break;


            default:
                timeResult = String.format("%tA%n", getDateFormat(fDateStr));
                break;
        }
        if (Math.abs(result) > 7) {//假如时间大于7天
            timeResult = fDateStr;
        }
        return timeResult;
    }

    /**
     * 判断时间相差几天
     *
     * @param fDate yyyy-MM-dd 格式
     * @param oDate 应写当前时间
     * @return 时间为-1时，请检查代码
     * @throws ParseException 
     */
    public static int daysOfTwo(String fDateStr, String oDateStr) throws ParseException {
        Date fDate = getDateFormat(fDateStr);
        Date oDate = getDateFormat(oDateStr);
        Calendar aCalendar = Calendar.getInstance();
        aCalendar.setTime(fDate);
        int day1 = aCalendar.get(Calendar.DAY_OF_YEAR);
        aCalendar.setTime(oDate);
        int day2 = aCalendar.get(Calendar.DAY_OF_YEAR);
        return day2 - day1;
    }


    /**
     * 将时间转换为 Date类型
     *
     * @param time yyyy-MM-dd格式
     * @return
     * @throws ParseException 
     */
    public static Date getDateFormat(String time) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.parse(time);
    }


}